import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:flutter/material.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/core/withdraw_deposit_manager/withdraw_deposit_manager.dart';
import 'package:flutter_app_unionad/event_or_delegate/reload_event.dart';
import 'package:flutter_app_unionad/model/partner_count_data_model.dart';
import 'package:flutter_app_unionad/model/partner_income_list_model.dart';
import 'package:flutter_app_unionad/model/partner_ship_info_model.dart';
import 'package:flutter_app_unionad/model/partner_ship_pay_model.dart';
import 'package:flutter_app_unionad/model/take_save_model.dart';
import 'package:flutter_app_unionad/request/partner_ship_request.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/basice/my_separator_widget.dart';
import 'package:flutter_app_unionad/ui/basice/title_alert_widget.dart';
import 'package:flutter_app_unionad/ui/my_facility/widget/select_pay_type_widget.dart';
import 'package:flutter_app_unionad/ui/partnership/partnership_page.dart';
import 'package:flutter_app_unionad/ui/promotion/delegate/account_amount_delegate.dart';
import 'package:flutter_app_unionad/view_model/change_device_event.dart';

import 'add_facility_widget.dart';
import 'package:tobias/tobias.dart' as tobias;
import 'package:fluwx/fluwx.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class PartnerShipWidget extends StatefulWidget {
  final PartnershipPageDelegate? delegate;

  const PartnerShipWidget({
    Key? key,
    this.delegate,
  }) : super(key: key);

  @override
  _PartnerShipWidgetState createState() => _PartnerShipWidgetState();
}

class _PartnerShipWidgetState extends State<PartnerShipWidget> with AccountAmountDelegate {
  PartnerCountDataModel? partnerCountDataModel;
  List<PartnerIncomeListModel>? dataSource;
  int page = 0;
  EasyRefreshController? _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();

    thirdPayListen();
    getPartnerData(needList: true);
    eventBus.on<TabViewReloadDataEvent>().listen((event) {
      print('TabViewReloadDataEvent');
      if (event.index == 2) {
        getPartnerData(needList: false);
      }
    });
  }

  void getData() {
    page = 1;
    PartnerShipRequest.getPartnerIncomeList(pageNum: page).then((value) {
      if (dataSource == null) dataSource = [];
      dataSource?.clear();
      dataSource?.addAll(value);
      if (mounted) setState(() {});
    });
  }

  void getMoreData() {
    page++;
    PartnerShipRequest.getPartnerIncomeList(pageNum: page).then((value) {
      if (dataSource == null) dataSource = [];
      dataSource?.addAll(value);
      if (dataSource != null && dataSource!.length < 20) {
        _controller!.finishLoadCallBack?.call();
      } else {
        _controller!.resetLoadStateCallBack?.call();
      }
      if (mounted) setState(() {});
    });
  }

  void getPartnerData({bool needList = false}) {
    PartnerShipRequest.partnerCountDataRequest().then((value) {
      if (needList) getData();
      if (mounted) {
        setState(() {
          partnerCountDataModel = value;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (partnerCountDataModel == null) return ProgressDialog.showFirstLoading();
    return Column(
      children: [
        buildTopLogoAndTotalMoneyWidget(),
        MySizeBox(height: 20),
        buildTopMoneyDetailWidget(),
        MySizeBox(height: 10),
        buildTopDetailWidget(),
        MySizeBox(height: 5),
        Expanded(child: buildBottomContentWidget()),
        MySizeBox(height: 30),
        buildBottomButtonWidget(context),
        MySizeBox(height: 30),
      ],
    );
  }

  Widget buildBottomButtonWidget(BuildContext context) {
    bool result = partnerCountDataModel!.totalDevNum! < int.parse(Configuration().maxCount);
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        MyButton(
          title: "提现",
          width: 135.px,
          height: 40.px,
          titleStyle: TextStyle(
            color: Colors.white,
            fontWeight: MyFontWeight.bold,
            fontSize: MyFont.font14,
          ),
          onTap: () {
            //
            WithdrawDepositManager.withdrawDeposit(context, this);
            // if (this.widget.delegate != null) this.widget.delegate.withdraw();
          },
        ),
        MySizeBox(width: 15),
        MyButton(
          title: "新购设备",
          width: 135.px,
          height: 40.px,
          titleStyle: TextStyle(
            color: Colors.white,
            fontWeight: MyFontWeight.bold,
            fontSize: MyFont.font14,
          ),
          onTap: () {
            //
            if (result) {
              addFacility();
            } else {
              ShowCenterAlertDialog.showAlert(context, height: 170.px, builder: (ctx) {
                return TitleAlertWidget(
                  title: "提示",
                  subTitle: "您已超过最大购买数量",
                  actions: ["取消", "联系客服"],
                  actionsColors: [Colors.black12, MyColors.color_245_174_41],
                  actionsTitleColors: [Colors.white, Colors.white],
                  onTap: (index) {
                    if (index == 0) {
                      Navigator.pop(context, false);
                    } else {
                      Navigator.pop(context, true);
                    }
                  },
                );
              }).then(
                (value) {
                  if (value != null && value) {
                    Configuration().call();
                  }
                },
              );
            }
          },
        ),
      ],
    );
  }

  Widget buildBottomContentWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.px),
      ),
      padding: EdgeInsets.symmetric(horizontal: 35.px, vertical: 20.px),
      child: Column(
        children: [
          Row(
            children: [
              Text(
                "昨日收益明细",
                style: TextStyle(
                  color: MyColors.color_27_27_27,
                  fontSize: MyFont.font14,
                  fontWeight: MyFontWeight.bold,
                ),
              ),
              Expanded(child: SizedBox()),
              GestureDetector(
                onTap: () {
                  if (this.widget.delegate != null) this.widget.delegate!.facilityList();
                },
                child: Text(
                  "设备列表",
                  style: TextStyle(
                    decoration: TextDecoration.underline,
                    color: MyColors.formHex("#F8BA35FF"),
                    fontSize: MyFont.font12,
                    fontWeight: MyFontWeight.regular,
                  ),
                ),
              ),
            ],
          ),
          MySizeBox(height: 10),
          MySeparator(height: 2, color: MyColors.color_238_238_238),
          MySizeBox(height: 10),
          Expanded(child: buildListView()),
          MySizeBox(height: 10),
        ],
      ),
    );
  }

  Widget buildListView() {
    if (dataSource == null || dataSource?.length == 0) {
      return EmptyWidget();
    }
    return EasyRefresh(
      header: RefreshBasics.header,
      footer: RefreshBasics.footer,
      controller: _controller,
      onRefresh: () async {
        getPartnerData(needList: false);
        getData();
      },
      onLoad: () async {
        getMoreData();
      },
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: dataSource!.length,
        itemBuilder: (ctx, index) {
          return buildContentItem(index);
        },
      ),
    );
  }

  Widget buildContentItem(int index) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 5.px),
      child: Row(
        children: [
          Expanded(
            child: Row(
              children: [
                Container(
                  width: 100.px,
                  child: Text(
                    "设备: ${dataSource![index].devId}",
                    style: TextStyle(
                      color: MyColors.color_27_27_27,
                      fontWeight: MyFontWeight.regular,
                      fontSize: MyFont.font10,
                    ),
                  ),
                ),
                Text(
                  "${DateTime.fromMillisecondsSinceEpoch(dataSource![index].createTime!.toInt()).toString().split(' ').first}",
                  style: TextStyle(
                    color: MyColors.color_27_27_27,
                    fontWeight: MyFontWeight.regular,
                    fontSize: MyFont.font10,
                  ),
                ),
              ],
            ),
          ),
          Text(
            "+ ${dataSource![index].totalIncome}",
            style: TextStyle(
              color: MyColors.color_27_27_27,
              fontWeight: MyFontWeight.regular,
              fontSize: MyFont.font10,
            ),
          ),
        ],
      ),
    );
  }

  Widget buildTopDetailWidget() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5.px),
      ),
      height: 90.px,
      alignment: Alignment.center,
      child: IntrinsicHeight(
        child: Row(
          children: [
            Container(
              width: (SizeFill.screenWidth! - 20.px - 2) / 3,
              child: buildTopMoneyDetailItem("闲置设备", "${partnerCountDataModel!.idleNum}"),
            ),
            VerticalDivider(width: 1, color: MyColors.color_238_238_238),
            Container(
              width: (SizeFill.screenWidth! - 20.px - 2) / 3,
              child: buildTopMoneyDetailItem("运行设备", "${partnerCountDataModel!.runningNum}"),
            ),
            VerticalDivider(width: 1, color: MyColors.color_238_238_238),
            Container(
              width: (SizeFill.screenWidth! - 20.px - 2) / 3,
              child: buildTopMoneyDetailItem("总设备", "${partnerCountDataModel!.totalDevNum}"),
            ),
          ],
        ),
      ),
    );
  }

  Widget buildTopMoneyDetailWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      children: [
        buildTopMoneyDetailItem("昨日收益", "+${partnerCountDataModel!.ytdIncome}"),
        buildTopMoneyDetailItem("累积收益", partnerCountDataModel!.totalIncome.toString()),
        buildTopMoneyDetailItem("最近七天", partnerCountDataModel!.recent7DaysIncome.toString()),
      ],
    );
  }

  Widget buildTopMoneyDetailItem(String title, String money) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            color: MyColors.color_27_27_27,
            fontWeight: MyFontWeight.regular,
            fontSize: MyFont.font13,
          ),
        ),
        MySizeBox(height: 5),
        Text(
          money,
          style: TextStyle(
            color: MyColors.color_27_27_27,
            fontWeight: MyFontWeight.bold,
            fontSize: MyFont.font16,
          ),
        )
      ],
    );
  }

  Widget buildTopLogoAndTotalMoneyWidget() {
    int max = (partnerCountDataModel!.withdrawalAmount!.toDouble() / int.parse(Configuration().price)).floor();
    return Container(
      height: 86.px,
      width: double.infinity,
      child: Stack(
        children: [
          if (max > 0)
            Positioned(
              top: 21.px,
              right: 30.px,
              child: GestureDetector(
                child: MyAssetImage("icon_logo_money"),
                onTap: () {
                  addFacility(max: max);
                  // if (this.widget.delegate != null) this.widget.delegate.pointMoney();
                },
              ),
              width: 66.px,
              height: 65.px,
            ),
          Center(
            child: Column(
              children: [
                MySizeBox(height: 15),
                Text(
                  "可提现金额",
                  style: TextStyle(
                    color: MyColors.formHex("#000000FF"),
                    fontSize: MyFont.font13,
                    fontWeight: MyFontWeight.regular,
                  ),
                ),
                Text(
                  "${partnerCountDataModel!.withdrawalAmount}",
                  style: TextStyle(
                    color: MyColors.formHex("#272727FF"),
                    fontSize: MyFont.font33,
                    fontWeight: MyFontWeight.bold,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  addFacility({int? max}) {
    ShowCenterAlertDialog.showAlert(
      context,
      width: 356.px,
      height: 272.px,
      radius: 10.px,
      builder: (ctx) {
        return AddFacilityWidget(
          isMoney: max != null,
          max: max != null ? max : int.parse(Configuration().maxCount) - partnerCountDataModel!.totalDevNum!.toInt(),
          reloadOnTap: (String number) {
            if (max != null) {
              selectPay("0", number);
            } else {
              ShowBottomAlertDialog.showBottomDialog(context, height: 216.px + SizeFill.statusHeight!, builder: (ctx) {
                return SelectPayTypeWidget(
                  weChatPayOnTop: () {
                    selectPay('1', number);
                  },
                  alipayPayOnTop: () {
                    selectPay('2', number);
                  },
                );
              });
            }
          },
        );
      },
    );
  }

  void selectPay(String pay, String number) {
    print("开始支付$pay");
    ProgressDialog.showPayFirstLoading(context);
    PartnerShipRequest.partnerShipPayRequest(num: number, payType: pay).then((value) {
      ProgressDialog.dismiss(context);
      if (value != null) {
        if (pay == '0') {
          ShowToastWidget.showToast(msg: '支付成功');
          getPartnerData();

          return;
        } else if (pay == '1') {
          //微信支付
          payThird(value, 0);
        } else {
          //支付宝
          payThird(value, 1);
        }
      }
    });
  }

  void payThird(PartnerShipPayModel orderModel, int type) async {
    if (type == 0) {
      //微信支付

      final future = await payWithWeChat(
        appId: orderModel.appId!,
        partnerId: orderModel.partnerid!,
        prepayId: orderModel.prepayid!,
        packageValue: orderModel.package!,
        nonceStr: orderModel.nonceStr!,
        timeStamp: int.parse(orderModel.timeStamp!),
        sign: orderModel.paySign!,
      );
      print(future);
      if (future == null || !future) {
        ShowToastWidget.showToast(msg: "支付失败");
      }
    } else if (type == 1) {
      //支付宝支付
      print("支付宝支付 ---$orderModel");
      tobias.aliPay(orderModel.payInfo!).then((value) {
        print(value["resultStatus"]);
        if (value["resultStatus"] == "9000") {
          getPartnerData();
          ShowToastWidget.showToast(msg: '支付成功');
        } else {
          ShowToastWidget.showToast(msg: value["memo"]);
        }
      });
    }
  }

//微信支付监听
  void thirdPayListen() async {
    weChatResponseEventHandler.listen((res) {
      if (res is WeChatPaymentResponse) {
        print(res.errCode);
        if (res.errCode == null || res.errCode == 0) {
          //支付成功
          getPartnerData();

          ShowToastWidget.showToast(msg: '支付成功');
        } else {
          ShowToastWidget.showToast(msg: res.errStr == null || res.errStr!.length == 0 ? "支付失败" : res.errStr!);
        }
      }
    });
//    _pay = _alipay.payResp().listen(_listenPay);
  }

  @override
  void reloadAmount() {
    // TODO: implement reloadAmount
    getPartnerData();
  }

  @override
  void reloadAmountWithOpen(TaskSaveModel point) {
    // TODO: implement reloadAmountWithOpen
  }
}
